// 处理用户 登录/注册/登出 等操作
import { IUser } from 'screens/project-list/search-panel'
import { apiURL } from 'screens/project-list'
const localStorageKey = '__auto_provider_token__'

export interface IAuthForm {
  username: string
  password: string
}

// 获取token
export const getToken = () => window.localStorage.getItem(localStorageKey)

//保存token
export const handleUserResponse = ({ user }: { user: IUser }) => {
  window.localStorage.setItem(localStorageKey, user.token || '')
  return user
}

// 删除token
export const logout = async () => window.localStorage.removeItem(localStorageKey)

// 用户登录
export const login = (data: IAuthForm) => {
  return fetch(`${apiURL}/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  }).then(async response => {
    if (response.ok) {
      return handleUserResponse(await response.json())
    } else {
      return Promise.reject(response.json())
    }
  })
}

// 用户注册
export const register = (data: IAuthForm) => {
  return fetch(`${apiURL}/register`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  }).then(async response => {
    if (response.ok) {
      return handleUserResponse(await response.json())
    } else {
      return Promise.reject(response.json())
    }
  })
}
